package com.ourcraft.informationcollectionsystem.service.province.uploadData;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ourcraft.informationcollectionsystem.entity.DataReportForm;
import com.ourcraft.informationcollectionsystem.entity.DTO.ReportDataContainer;
import com.ourcraft.informationcollectionsystem.mapper.DataReportFormMapper;
import com.ourcraft.informationcollectionsystem.mapper.InvestigationPeriodMapper;
import com.ourcraft.informationcollectionsystem.utils.statusCode.DataReportFormStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
//import org.springframework.web.reactive.function.client.WebClient;

@Service
public class UploadCollectedDataServiceImpl implements UploadCollectedDataService {
    @Autowired
    private DataReportFormMapper dataReportFormMapper;
    @Autowired
    private InvestigationPeriodMapper investigationPeriodMapper;

    static final String BASE_UPLOAD_URL = "http://localhost:8888";
    static final String SPECIFIC_UPLOAD_URI = "/common/queryHistory/testUpload";

    @Override
    public Boolean upload(Integer investigationId){
        var jsonString = generateJSON(investigationId);
        dataReportFormMapper.updateDataReportFormStatus(investigationId);
        System.out.println(jsonString);

//        var webClient = WebClient.builder()
//                .baseUrl(BASE_UPLOAD_URL)
//                .defaultCookie("cookie-name", "cookie-value")
//                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
//                .build();
//
//        webClient.post()
//                .uri(SPECIFIC_UPLOAD_URI)
//                .contentType(MediaType.APPLICATION_JSON)
//                .bodyValue(jsonString)
//                .retrieve()
//                .toBodilessEntity();
        return true;
    }

    private String generateJSON(Integer investigationId) {
        var wrapper = new QueryWrapper<DataReportForm>()
                .eq("form_examine_status", DataReportFormStatus.PASS.ordinal())
                .eq("investigation_id", investigationId);
        var passedForm = dataReportFormMapper.selectList(wrapper);

        Integer startTotalNum = 0;
        Integer endTotalNum = 0;
        for(var form : passedForm){
            startTotalNum += form.getFormStartTotalNum();
            endTotalNum += form.getFormEndTotalNum();
        }

        var inv = investigationPeriodMapper.selectById(investigationId);
        var uploadData = new ReportDataContainer(
                inv.getInvestigationStartDate(),
                inv.getInvestigationLength(),
                startTotalNum,
                endTotalNum,
                passedForm
        );

        return JSON.toJSONString(uploadData);
    }
}
